/*
 * ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is
 *
 * java-concurrency-presentation:
 * concurrency presentation tutorial.
 *
 * The Initial Developer of the Original Code is
 * Marco Antonio Villalobos, Jr.
 * Portions created by the Initial Developer are Copyright (C) 2010
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s): None.
 *
 * ***** END LICENSE BLOCK *****
 */

package presentation.concurrency.bad;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * An example that shows why ignoring concurrency will fail.
 *
 * It will have fixed number of threads change the state of a mutable object,
 * with a simple incrementing method.
 *
 * This will internally force context switching to increase chances of failure.
 */
public class BadConcurrencyExample {

    /**
     * Executes this example.
     */
    public void execute() throws InterruptedException {

        ExecutorService executorService = Executors.newFixedThreadPool(100);        //create 100 threads

        Mutable mutable = new Mutable();

        int no_of_threads = 1000;
        int iterations = 1000;
        double increment = 10d;

        for (int i=0;i< no_of_threads;i++) {
            executorService.submit(                                                 //submit the threads
                    new Radiation(iterations, mutable, increment)
            );
        }

        try {
            executorService.shutdown();                                             //signal a shutdown
        } finally {
            executorService.awaitTermination(                                       //wait for all threads to finish
                    Long.MAX_VALUE, TimeUnit.DAYS
            );
        }

        double expected = no_of_threads * iterations * increment;

        System.out.println("actual:  " + mutable.getValue()+", expected:  "+expected);
    }

    /**
     * Executes this example as a program.
     */
    public static void main(String[] args) throws Exception {
        new BadConcurrencyExample().execute();
    }
}
